package com.sa.gateway.filter;

import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author Architecture Station
 * @version 1.0
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter {

    // 登录URL
    private static final String LOGIN_URL = "/api/auth/login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 解决SaTokenContextException: 未能获取有效的上下文的问题
        SaReactorSyncHolder.setContext(exchange);

        // 如果请求路径包含登录URL，则直接放行
        if (exchange.getRequest().getPath().toString().contains(LOGIN_URL)) {
            return chain.filter(exchange);
        }

        // 检查是否登录
        if (!StpUtil.isLogin()) {
            return buildErrorResponse(exchange, "用户未登录");
        }

        // 在此处可以添加其他权限检查逻辑
        // 比如：检查用户角色、权限等
        // if (!StpUtil.hasPermission("some_permission")) {
        //     return buildErrorResponse(exchange, "权限不足");
        // }

        // 如果已登录且有权限，继续处理后续的过滤器链
        return chain.filter(exchange);
    }

    private Mono<Void> buildErrorResponse(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK); // 设置响应码为200
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);

        String jsonResponse = String.format("{\"code\":500, \"msg\":\"%s\"}", message);
        byte[] bytes = jsonResponse.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        return response.writeWith(Flux.just(buffer));
    }
}
















